import Hashs from 'jshashes';
import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Input, Select, Button, Card, Row, Col, message, Divider, Tree, Menu } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Profile.less';

const { TreeNode } = Tree;
const FormItem = Form.Item;
const { Option } = Select;
// use permission as a parameter

@connect(({ auth, loading }) => ({
  auth,
  loading: loading.effects['auth/fetch'],
}))
@Form.create()
export default class EditAccount extends Component {
  state = {
    loading: false,
    checkedKeys: [], // 树形菜单选中的key
    selectedKeys: [], //  城市菜单选中的key
    selectAppSysPerm: '', //  当前选中的平台key
    appSysPerm: [], //  所有选中的平台key
    appMenu: {}, // 记录所有平台的菜单key数组
  };
  componentDidMount() {
    this.props.dispatch({
      type: 'auth/fetchApp',
    });
    this.props.dispatch({
      type: 'auth/fetchName',
    });
  }
  onCheck = (checkedKeys, e) => {
    //console.log('halfcheck', e.halfCheckedKeys);
    //console.log('checkedKeys', checkedKeys);
    const { appMenu, selectAppSysPerm } = this.state;
    appMenu[selectAppSysPerm] = { checked: checkedKeys, halfChecked: e.halfCheckedKeys };
    //console.log('appmenua', appMenu);
    this.setState({ checkedKeys, appMenu });
  };

  onSelect = checkedKeys => {
    //console.log('onSelect', checkedKeys);
    this.setState({ selectedKeys: checkedKeys });
  };
  onApp = ({ key, selectedKeys }) => {
    const { appMenu } = this.state;
    let CurrentselectKeys = [];
    if (key !== '') {
      CurrentselectKeys = appMenu[key];
    }

    //console.log('CurrentselectKeys', CurrentselectKeys);
    this.props.dispatch({
      type: 'auth/fetchMenuAuth',
      payload: { appId: key },
    });
    this.props.dispatch({
      type: 'auth/fetchDataAuth',
      callback: () => {
        //console.log('callback');
        this.setState({
          appSysPerm: selectedKeys,
          selectAppSysPerm: key,
          checkedKeys: CurrentselectKeys,
        });
      },
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (
          this.state.selectedKeys.length === 0 ||
          this.state.checkedKeys.length === 0 ||
          !this.state.appSysPerm
        ) {
          message.error('平台/菜单/数据权限选择不能为空');
        } else {
          const { appMenu, appSysPerm } = this.state;

          let unionArray = [];
          for (let elem of appSysPerm.values()) {
            const temp = appMenu[elem];
            unionArray = unionArray.concat(temp.checked, temp.halfChecked);
          }
          //console.log('unionarry', unionArray);
          const accountvalues = {
            ...values,
            password: new Hashs.SHA1().hex(values.password),
            amDataPerm: this.state.selectedKeys,
            amMenuPerm: unionArray,
            appSysPerm: this.state.appSysPerm,
          };
          //console.log('values', accountvalues);
          this.props.dispatch({
            type: 'auth/addAccount',
            payload: { ...accountvalues },
            callback: () => {
              message.success('添加账号资料成功！');
              this.props.history.push(`/usermanage/acmanage`);
            },
          });
        }
      }
    });
  };
  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.label} key={item.id} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.label} {...item} />;
    });
  render() {
    const {
      auth: { AppSysPerm, MenuAuth, DataAuth, roleName },
      form,
    } = this.props;
    const { getFieldDecorator } = form;

    return (
      <PageHeaderLayout title="编辑个人信息">
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} style={{ marginTop: 8 }}>
            <Row gutter={16}>
              <Col span={8}>
                <Card title="平台权限" bordered={false} bodyStyle={{ height: 400 }}>
                  <Menu style={{ width: 200 }} onSelect={this.onApp} multiple>
                    {AppSysPerm.map(item => (
                      <Menu.Item key={item.appId}>{item.appName}</Menu.Item>
                    ))}
                  </Menu>
                </Card>
              </Col>
              <Col span={8}>
                <Card
                  title="菜单权限"
                  bordered={false}
                  bodyStyle={{ height: 300, overflowY: 'auto' }}
                >
                  <Tree
                    checkable
                    autoExpandParent
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                  >
                    {this.renderTreeNodes(MenuAuth)}
                  </Tree>
                </Card>
              </Col>
              <Col span={8}>
                <Card
                  title="数据权限"
                  bordered={false}
                  bodyStyle={{ height: 300, overflowY: 'auto' }}
                >
                  <Tree
                    checkable
                    autoExpandParent
                    onCheck={this.onSelect}
                    checkedKeys={this.state.selectedKeys}
                  >
                    {this.renderTreeNodes(DataAuth)}
                  </Tree>
                </Card>
              </Col>
            </Row>
            <Divider />
            <Row>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="用户名：">
                  {getFieldDecorator('userName', {
                    rules: [{ required: true, message: '请输入用户名...' }],
                  })(<Input />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="角色名称：">
                  {getFieldDecorator('roleName')(
                    <Select allowClear="true" placeholder="请选择" style={{ width: '100%' }}>
                      {roleName.map(item => (
                        <Option value={item.code}>{item.name}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="公司名称：">
                  {getFieldDecorator('userOrgName', {
                    //  rules: [{ required: true, message: '请输入设备名称...' }],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="账号类型：">
                  {getFieldDecorator('accountType', {
                    rules: [{ required: true, message: '请选择帐号类型...' }],
                  })(
                    <Select
                      allowClear="true"
                      placeholder="请选择帐号类型"
                      style={{ width: '100%' }}
                    >
                      <Option value={0}>普通账号</Option>
                      <Option value={1}>管理员账号</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="角色类型：">
                  {getFieldDecorator('roleType', {
                    rules: [{ required: true, message: '请选择角色类型' }],
                  })(
                    <Select
                      allowClear="true"
                      placeholder="请选择角色类型"
                      style={{ width: '100%' }}
                    >
                      <Option value={0}>监管部门</Option>
                      <Option value={1}>企业</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="密码：">
                  {getFieldDecorator('password', {
                    rules: [{ required: true, message: '请输入密码' }],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="姓名：">
                  {getFieldDecorator('fullName', {
                    //  rules: [{ required: true, message: '请输入设备名称...' }],
                  })(<Input />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="性别：">
                  {getFieldDecorator('gender', {
                    rules: [{ required: true, message: '请选择性别' }],
                  })(
                    <Select allowClear="true" placeholder="请选择" style={{ width: '100%' }}>
                      <Option value={0}>男</Option>
                      <Option value={1}>女</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="安全等级：">
                  {getFieldDecorator('safeGrade', {
                    //  rules: [{ required: true, message: '请输入公司名称!' }],
                  })(
                    <Select allowClear="true" placeholder="请选择" style={{ width: '100%' }}>
                      <Option value={0}>弱</Option>
                      <Option value={1}>中</Option>
                      <Option value={2}>强</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="证件类型：">
                  {getFieldDecorator(
                    'licType',
                    {}
                  )(
                    <Select allowClear="true" placeholder="请选择" style={{ width: '100%' }}>
                      <Option value={0}>营业执照</Option>
                      <Option value={1}>身份证</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="证件号码：">
                  {getFieldDecorator('licNo', {
                    rules: [{ required: true, message: '请输入证件号码' }],
                  })(<Input />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="所在城市：">
                  {getFieldDecorator('city', {
                    rules: [{ required: true, message: '请输入所在城市' }],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="手机号：">
                  {getFieldDecorator('mobPhone', {
                    //  rules: [{ required: true, message: '请输入车队名称...' }],
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="邮箱：">
                  {getFieldDecorator('email', {
                    //  rules: [{ required: true, message: '请输入车队名称...' }],
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} label="传真：">
                  {getFieldDecorator('fax', {
                    //  rules: [{ required: true, message: '请输入公司名称!' }],
                  })(<Input placeholder="请输入" />)}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col span={24} offset={10}>
                <Button
                  type="primary"
                  htmlType="submit"
                  style={{ width: 200, height: 50 }}
                  loading={this.state.loading}
                  onSubmit={this.handleSubmit}
                >
                  提交
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}
